use crate::vm::VirtualMachine;
use crate::advanced_optimizations::{OptimizationManager, OptimizationLevel};
use crate::compiler::SplitCompiler;
use crate::error::Result;

/// 性能优化配置
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PerformanceProfile {
    /// 开发配置：快速编译，低优化
    Development,
    /// 生产配置：平衡编译速度和运行时性能
    Production,
    /// 高性能配置：最高级别的优化，可能增加编译时间
    HighPerformance,
    /// 自定义配置：用户可以手动调整各个优化选项
    Custom,
}

/// 高级性能优化工具
pub struct PerformanceOptimizer {
    profile: PerformanceProfile,
    enable_simd: bool,
    enable_aggressive_inlining: bool,
    enable_predictive_optimization: bool,
    enable_memory_optimizations: bool,
    enable_concurrent_gc: bool,
}

impl PerformanceOptimizer {
    /// 创建一个新的性能优化器
    pub fn new(profile: PerformanceProfile) -> Self {
        let (enable_simd, enable_aggressive_inlining, enable_predictive_optimization, enable_memory_optimizations, enable_concurrent_gc) = 
            match profile {
                PerformanceProfile::Development => (
                    false,   // 禁用SIMD以加速编译
                    false,   // 禁用激进内联
                    false,   // 禁用预测优化
                    false,   // 禁用高级内存优化
                    true,    // 仍启用并发GC以改善开发体验
                ),
                PerformanceProfile::Production => (
                    true,    // 启用SIMD
                    false,   // 禁用激进内联以平衡编译时间
                    true,    // 启用预测优化
                    true,    // 启用内存优化
                    true,    // 启用并发GC
                ),
                PerformanceProfile::HighPerformance => (
                    true,    // 启用SIMD
                    true,    // 启用激进内联
                    true,    // 启用预测优化
                    true,    // 启用内存优化
                    true,    // 启用并发GC
                ),
                PerformanceProfile::Custom => (
                    true,    // 默认值，用户可以自定义
                    false,   // 默认值，用户可以自定义
                    true,    // 默认值，用户可以自定义
                    true,    // 默认值，用户可以自定义
                    true,    // 默认值，用户可以自定义
                ),
            };

        PerformanceOptimizer {
            profile,
            enable_simd,
            enable_aggressive_inlining,
            enable_predictive_optimization,
            enable_memory_optimizations,
            enable_concurrent_gc,
        }
    }

    /// 启用或禁用SIMD优化
    pub fn set_simd(&mut self, enable: bool) -> &mut Self {
        self.enable_simd = enable;
        self
    }

    /// 启用或禁用激进内联
    pub fn set_aggressive_inlining(&mut self, enable: bool) -> &mut Self {
        self.enable_aggressive_inlining = enable;
        self
    }

    /// 启用或禁用预测优化
    pub fn set_predictive_optimization(&mut self, enable: bool) -> &mut Self {
        self.enable_predictive_optimization = enable;
        self
    }

    /// 启用或禁用高级内存优化
    pub fn set_memory_optimizations(&mut self, enable: bool) -> &mut Self {
        self.enable_memory_optimizations = enable;
        self
    }

    /// 启用或禁用并发垃圾回收
    pub fn set_concurrent_gc(&mut self, enable: bool) -> &mut Self {
        self.enable_concurrent_gc = enable;
        self
    }

    /// 优化虚拟机配置以获得最佳性能
    pub fn optimize_vm(&self, vm: &mut VirtualMachine) -> Result<()> {
        // 设置优化级别
        let optimization_level = match self.profile {
            PerformanceProfile::Development => OptimizationLevel::Basic,
            PerformanceProfile::Production => OptimizationLevel::Medium,
            PerformanceProfile::HighPerformance => OptimizationLevel::Aggressive,
            PerformanceProfile::Custom => {
                if self.enable_aggressive_inlining {
                    OptimizationLevel::Aggressive
                } else {
                    OptimizationLevel::Medium
                }
            },
        };

        // 替换优化管理器
        let mut optimization_manager = OptimizationManager::new(optimization_level);
        optimization_manager.optimize_virtual_machine(vm)?;
        vm.optimization_manager = optimization_manager;

        // 配置内存优化
        if self.enable_memory_optimizations {
            // 可以在这里添加特定的内存优化配置
            // 例如：调整内存池大小，启用压缩等
        }

        // 配置并发GC
        if self.enable_concurrent_gc {
            vm.concurrent_gc.set_memory_limit(f64::MAX); // 无内存限制
        } else {
            vm.concurrent_gc.stop();
        }

        // 如果需要激进优化，启用激进优化模式
        if optimization_level == OptimizationLevel::Aggressive {
            vm.enable_aggressive_optimizations();
        }

        Ok(())
    }

    /// 优化编译器配置以获得最佳性能
    pub fn optimize_compiler(&self, compiler: &mut SplitCompiler) -> Result<()> {
        // 设置编译器后端的优化级别
        let optimization_level = match self.profile {
            PerformanceProfile::Development => OptimizationLevel::Basic,
            PerformanceProfile::Production => OptimizationLevel::Medium,
            PerformanceProfile::HighPerformance => OptimizationLevel::Aggressive,
            PerformanceProfile::Custom => {
                if self.enable_aggressive_inlining {
                    OptimizationLevel::Aggressive
                } else {
                    OptimizationLevel::Medium
                }
            },
        };

        // 获取后端的可变引用并更新优化级别
        let backend = compiler.get_backend_mut();
        backend.set_optimization_level(optimization_level);
        
        // 如果启用了激进内联，特别设置
        if self.enable_aggressive_inlining {
            backend.enable_aggressive_inlining();
        }

        // 如果启用了SIMD优化
        if self.enable_simd {
            backend.enable_simd_optimizations();
        }

        // 如果启用了JIT，确保JIT优化级别与总体优化级别一致
        #[cfg(feature = "jit")]
        if let Some(jit) = backend.get_jit_compiler_mut() {
            let jit_level = match optimization_level {
                OptimizationLevel::Basic => JITOptimizationLevel::Basic,
                OptimizationLevel::Medium => JITOptimizationLevel::Aggressive,
                OptimizationLevel::Aggressive => JITOptimizationLevel::Aggressive,
            };
            jit.set_optimization_level(jit_level);
        }

        Ok(())
    }

    /// 预热虚拟机以提高启动性能
    pub fn warmup_vm(&self, vm: &mut VirtualMachine) -> Result<()> {
        #[cfg(feature = "jit")]
        vm.warmup_critical_functions();
        
        Ok(())
    }
}